'use strict';

const crypto = require('crypto');
const Controller = require('egg').Controller;

class LoginController extends Controller {
  constructor(ctx) {
    super(ctx);
  }
  async signIn() {
    const { ctx, app, service } = this;

    ctx.validate({
      username: {type: 'string', required: true},
      password: {type: 'string', required: true}
    }, ctx.query);
    
    const password = crypto.createHmac('sha256', app.config.jwt.secret).update(ctx.query.password).digest('hex');

    const post = {
      username: ctx.query.username,
      password: password
    }

    const result = await service.login.signIn(post);


    let token
    if (result) {
      const data = {
        _id: result._id,
        username: result.username
      }
      token = await ctx.helper.createToken(data);
    }
    
    ctx.body = token || 'null';
  }
  // async create() {
  //   const { ctx, service } = this;
  //   // 5a4d9bbd18863a19b029bded
  //   const result = await service.user.create({username: 'gg', password: 'gg'});

  //   // const result = await service.user.updatePassword('5a4d9bbd18863a19b029bded', 'e7bd17bafbcbf73e0e0bc2cb7fdd96a85196597aef0d70dcf34a3f5a16641134');

  //   ctx.body = result;
  //   ctx.status = 201;
  // }
}

module.exports = LoginController;
